# !/usr/bin/env python
# _*_ coding:utf-8 _*_
import json

from django_redis import get_redis_connection

from utils.cookiesecret import CookieSecret


def merge_cart_cookie_to_redis(request, response):
    # 1. cookie---覆盖--redis数据
    # 1.cookie数据
    cookie_str = request.COOKIES.get('carts')

    # 2. redis链接
    redis_client = get_redis_connection('carts')

    if cookie_str:
        cookie_cart_dict = CookieSecret.loads(cookie_str)
        # 3. for 遍历覆盖
        for sku_id in cookie_cart_dict:
            sku_dict = cookie_cart_dict[sku_id]
            redis_client.hset(request.user.id, sku_id, json.dumps(sku_dict))

        # 4. 删除cookie
        response.delete_cookie('carts')
